package core;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.List;

import core.Record.RecordType;

public class TCPResponse {

	int length = 0;
	MXitCommandType cmd;
	MXitErrorType err;
	String errMsg = "";
	List<String> data;
	
	private TCPResponse(int cmdId,String[] data,int errCode) {
		this.cmd = MXitCommandType.cmd(cmdId);
		this.err = MXitErrorType.code(errCode);
	}
	private TCPResponse(int len,int cmdId,String[] data,int errCode,String errMsg) {
		this(cmdId,data,errCode);
		this.errMsg = errMsg;
		this.length = len;	
	}
	
	public MXitCommandType getCmd() {
		return this.cmd;
	}
	
	public MXitError getMXitError() {
		return new MXitError(this.err,this.errMsg);
	}
	
	public String[] getData() {
		return this.data.toArray(new String[0]); 
	}
	
	public static TCPResponse Parse(byte[] data) throws UnsupportedEncodingException {
		
		String[] parts = new String(data,"US-ASCII").split(Record.END);
		int cmdId = Integer.parseInt(parts[0]);
		
		String[] errParts = parts[1].split(Field.END);		
		int errCode = Integer.parseInt(errParts[0]);
		
		String errMsg = "";
		if(errParts.length>1)
		{
			errMsg = errParts[1];
		}
		
		String[] dataParts = Arrays.copyOfRange(parts,2,parts.length);
		
		return new TCPResponse(data.length,cmdId,dataParts,errCode,errMsg);
	}
	
	public class MXitError {
		
		public final MXitErrorType type;
		public final String errMsg;
		
		public MXitError(MXitErrorType type,String errMsg) {
			this.type = type;
			this.errMsg = errMsg;
		}			
	}
}
